import {
  Body,
  Controller,
  Get,
  Inject,
  Post,
  Provide,
  Query,
  ALL,
  Put,
  Param,
  Del,
} from '@midwayjs/decorator';
import { OrderManageDTO } from '../dto/orderManage';
import { OrderManageService } from '../service/orderManage';
import { RoomManageService, RoomStatusEnum } from '../../roomManage/service/roomManage';
import { getDateFromUTC8 } from '../../../utils/date';

enum OrderStatusEnum {
  Sign = '1',
  UnSign = '0',
  Cancel = '2'
}

@Provide()
@Controller('/orderManage')
export class OrderManageController {
  @Inject()
  orderManageService: OrderManageService;

  @Inject()
  roomManageService: RoomManageService


  @Post('/', { description: '新建' })
  async create(@Body(ALL) data: OrderManageDTO) {
    data.remainingTime = '';
    data.startChargeDate = getDateFromUTC8(new Date(data.orderDate));
    data.endChargeDate = getDateFromUTC8(new Date(data.orderEndDate));
    return await this.orderManageService.createOrdered(data);
  }

  @Put('/', { description: '编辑' })
  async edit(@Body(ALL) data: OrderManageDTO) {
    const orderManage = await this.orderManageService.getById(data.id);
    // update
    if (!orderManage) {
      throw new Error('未找到该数据');
    }
    const updateData = { ...orderManage, ...data.toEntity() };
    const roomManage = await this.roomManageService.getById(data.roomId);
    if (!roomManage) {
      throw new Error('未找到该房间数据');
    }

    updateData.update_date = new Date();
    // 更改房间状态
    if (data.status == OrderStatusEnum.Sign) {
      roomManage.status = RoomStatusEnum.Enable;
    } else {
      roomManage.status = RoomStatusEnum.Disable;
    }
    await this.roomManageService.edit(roomManage);

    if (data.status == OrderStatusEnum.Sign) {
      return await this.orderManageService.orderedSign(updateData)
    }

    return await this.orderManageService.edit(updateData);
  }

  @Del('/:id', { description: '删除' })
  async remove(@Param('id') id: string) {
    const orderManage = await this.orderManageService.getById(id);
    await this.orderManageService.remove(orderManage);
  }

  @Get('/:id', { description: '根据id查询' })
  async getById(@Param('id') id: string) {
    return await this.orderManageService.getById(id);
  }

  @Get('/page', { description: '分页查询' })
  async page(@Query('page') page: number, @Query('size') size: number) {
    return await this.orderManageService.page(page, size);
  }

  @Get('/list', { description: '查询全部' })
  async list() {
    return await this.orderManageService.list();
  }

  @Get('/detail', { description: '详情' })
  async detail(@Query('id') id: string) {
    return await this.orderManageService.getDetailById(id);
  }
}